"""PersistentVolumeClaim资源Markdown写入器模块"""

from typing import Dict, Any, List
from src.writers.base import Writer
from src.utils.markdown_builder import MarkdownBuilder

class PersistentVolumeClaimWriter(Writer):
    """
    PersistentVolumeClaim资源Markdown写入器
    负责将提取的PVC资源信息写入Markdown文件
    """
    
    def write(self, data: Dict[str, Any], output_path: str) -> None:
        """
        将提取的PVC信息写入Markdown
        
        Args:
            data: 提取的PVC信息
            output_path: 输出文件路径
        """
        if not data or data.get("kind") != "PersistentVolumeClaim":
            self.logger.warning(f"无效的PersistentVolumeClaim数据: {data.get('name', '未知')}")
            return
        
        # 创建Markdown构建器
        md = self.create_markdown_builder()
        
        # 收集节标题，用于生成目录
        sections = ["基本信息", "存储配置", "状态"]
        
        # 标题
        md.header(f"PersistentVolumeClaim: {data.get('name', '未知')}", 1)
        
        # 命名空间
        md.bold("命名空间:").text(f" {data.get('namespace', 'default')}").newline(2)
        
        # 目录
        if len(sections) > 2:  # 只有当节较多时才添加目录
            md.toc(sections)
        
        # 基本信息
        self._write_basic_info(md, data)
        
        # 存储配置
        self._write_storage_config(md, data)
        
        # 状态信息
        self._write_status(md, data)
        
        # 生成Markdown文件
        self.write_markdown(md, output_path)
    
    def _write_basic_info(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入基本信息
        
        Args:
            md: Markdown构建器
            data: PVC数据
        """
        md.header("基本信息", 2)
        
        # 基本元数据表
        basic_info = {
            "名称": data.get("name", ""),
            "命名空间": data.get("namespace", "default"),
            "创建时间": data.get("creation_timestamp", "")
        }
        
        # 添加卷名称(如果有)
        if "volume_name" in data:
            basic_info["绑定卷"] = data.get("volume_name", "")
            
        # 存储类名
        if "storage_class_name" in data:
            basic_info["存储类"] = data.get("storage_class_name", "")
        
        md.dict_table(basic_info)
        
        # 标签和注解
        if data.get("labels"):
            md.header("标签", 3)
            md.dict_table(data.get("labels", {}))
        
        if data.get("annotations"):
            md.header("注解", 3)
            md.dict_table(data.get("annotations", {}))
    
    def _write_storage_config(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入存储配置信息
        
        Args:
            md: Markdown构建器
            data: PVC数据
        """
        md.header("存储配置", 2)
        
        spec = data.get("spec", {})
        if not spec:
            md.paragraph("未提供存储配置")
            return
        
        # 创建存储配置表
        storage_config = {}
        
        # 访问模式
        access_modes = spec.get("access_modes", [])
        if access_modes:
            # 翻译访问模式名称
            mode_map = {
                "ReadWriteOnce": "单节点读写",
                "ReadOnlyMany": "多节点只读",
                "ReadWriteMany": "多节点读写",
                "ReadWriteOncePod": "单Pod读写"
            }
            
            translated_modes = [mode_map.get(mode, mode) for mode in access_modes]
            storage_config["访问模式"] = ", ".join(translated_modes)
        
        # 存储要求
        resources = spec.get("resources", {})
        if resources and "requests" in resources:
            storage_config["存储请求"] = resources.get("requests", {}).get("storage", "")
        
        # 卷模式
        if "volume_mode" in spec:
            volume_mode = spec.get("volume_mode", "Filesystem")
            mode_map = {
                "Filesystem": "文件系统",
                "Block": "块设备"
            }
            storage_config["卷模式"] = mode_map.get(volume_mode, volume_mode)
        
        # 存储类名
        if "storage_class_name" in spec:
            storage_class = spec.get("storage_class_name", "")
            # 处理默认存储类标记
            if storage_class == "":
                storage_config["存储类"] = "默认存储类"
            else:
                storage_config["存储类"] = storage_class
        
        # 数据源
        if "data_source" in spec:
            data_source = spec.get("data_source", {})
            if data_source:
                source_type = data_source.get("kind", "")
                source_name = data_source.get("name", "")
                source_api = data_source.get("api_group", "")
                
                if source_name:
                    storage_config["数据源类型"] = source_type
                    storage_config["数据源名称"] = source_name
                    if source_api:
                        storage_config["数据源API组"] = source_api
        
        md.dict_table(storage_config)
        
        # 选择器
        selector = spec.get("selector", {})
        if selector:
            md.header("卷选择器", 3)
            
            # 匹配标签
            match_labels = selector.get("match_labels", {})
            if match_labels:
                md.header("匹配标签", 4)
                md.dict_table(match_labels)
            
            # 匹配表达式
            match_expressions = selector.get("match_expressions", [])
            if match_expressions:
                md.header("匹配表达式", 4)
                
                headers = ["键", "操作符", "值"]
                rows = []
                
                for expr in match_expressions:
                    key = expr.get("key", "")
                    operator = expr.get("operator", "")
                    values = expr.get("values", [])
                    
                    # 翻译operator为更友好的说明
                    operator_map = {
                        "In": "在列表中",
                        "NotIn": "不在列表中",
                        "Exists": "存在",
                        "DoesNotExist": "不存在"
                    }
                    operator = operator_map.get(operator, operator)
                    
                    rows.append([key, operator, ", ".join(values)])
                
                md.table(headers, rows)
    
    def _write_status(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入状态信息
        
        Args:
            md: Markdown构建器
            data: PVC数据
        """
        md.header("状态", 2)
        
        status = data.get("status", {})
        if not status:
            md.paragraph("未提供状态信息")
            return
        
        # 创建状态信息表
        status_info = {}
        
        # 阶段
        phase = status.get("phase", "")
        phase_map = {
            "Pending": "等待中",
            "Bound": "已绑定",
            "Lost": "已丢失",
            "Available": "可用",
            "Released": "已释放"
        }
        status_info["状态"] = phase_map.get(phase, phase)
        
        # 访问模式
        access_modes = status.get("access_modes", [])
        if access_modes:
            # 翻译访问模式名称
            mode_map = {
                "ReadWriteOnce": "单节点读写",
                "ReadOnlyMany": "多节点只读",
                "ReadWriteMany": "多节点读写",
                "ReadWriteOncePod": "单Pod读写"
            }
            
            translated_modes = [mode_map.get(mode, mode) for mode in access_modes]
            status_info["当前访问模式"] = ", ".join(translated_modes)
        
        # 容量
        if "capacity" in status:
            capacity = status.get("capacity", {})
            if "storage" in capacity:
                status_info["分配容量"] = capacity.get("storage", "")
        
        # 条件
        conditions = status.get("conditions", [])
        if conditions:
            recent_condition = conditions[-1]  # 取最新的条件
            cond_type = recent_condition.get("type", "")
            cond_status = recent_condition.get("status", "")
            cond_reason = recent_condition.get("reason", "")
            cond_message = recent_condition.get("message", "")
            
            status_info["最新条件"] = f"{cond_type}: {cond_status}"
            if cond_reason:
                status_info["原因"] = cond_reason
            if cond_message:
                status_info["消息"] = cond_message
        
        md.dict_table(status_info)
        
        # 如果有多个条件，列出所有条件
        if len(conditions) > 1:
            md.header("详细条件", 3)
            
            headers = ["类型", "状态", "上次转换", "原因", "消息"]
            rows = []
            
            for condition in conditions:
                cond_type = condition.get("type", "")
                cond_status = condition.get("status", "")
                last_transition = condition.get("last_transition_time", "")
                reason = condition.get("reason", "")
                message = condition.get("message", "")
                
                rows.append([cond_type, cond_status, last_transition, reason, message])
            
            md.table(headers, rows)